/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.swosh.stomp.web;

import cz.swosh.stomp.ejb.Person;
import cz.swosh.stomp.ejb.PersonDAO;
import cz.swosh.stomp.ejb.PersonWS;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileCleaningTracker;

/**
 *
 * @author upravil swosh, převzato od zslajchrt
 */
//@MultipartConfig in java ee 6
public class Controler extends HttpServlet {

    @EJB
    PersonDAO personDAO;
    @EJB
    PersonWS personWS;
    private File tmpDir;
    private static final String TMP_DIR_PATH = "/tmp";
    private File destinationDir;
    private List<FileItem> parsedReqL;
    private StringBuffer messageUpload;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        String realPath = getServletContext().getRealPath(TMP_DIR_PATH);
        tmpDir = new File(realPath);
        if (!tmpDir.isDirectory()) {
            tmpDir.mkdir();
            //throw new ServletException(TMP_DIR_PATH + " není adresář");
        }


    }

    /**
     * Meoda slouží jako kontroler. Všechny vstupy procházejí přes ni. Podle
     * parametru action dotazy rozřazuje podle toho, s jakou metodou bude zpracováván.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, String action)
            throws ServletException, IOException {
        String messageUploadOk = "";
        String messageUploadKo = "";
        messageUpload = new StringBuffer();
        if ("".equals(action) || action == null) {
            response.sendRedirect("/stompear-web/sprava/index.jsp?page=sprava");
        } else if ("upload".equals(action)) {
            doUpload(request, response);
            if (messageUpload.length() == 0) {
                messageUploadOk = "Osoba byla uložena. ";
            } else {
                messageUploadKo = messageUpload.toString();
            }      
            response.sendRedirect("/stompear-web/sprava/index.jsp?page=sprava&messageUploadOk=" + URLEncoder.encode(messageUploadOk, "utf-8")
                    + "&messageUploadKo=" + URLEncoder.encode(messageUploadKo, "utf-8"));
              }



    }

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        processRequest(request, response, action);
    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        String action;
        try {
        action = readStringParameter(request, "action");
        } catch (NullPointerException e){
            action = "";
        }
        processRequest(request, response, action);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Čte parametr z dotazu jako řetězec. Pokud je dotaz složen
     * z více částí, musíme ho načíst metodou readPartAsString.
     */
    private String readStringParameter(HttpServletRequest request,
            String parameter)
            throws IOException, ServletException {

        if (request.getContentType().startsWith("multipart/form-data")) {
            ServletFileUpload uploadHandler = new ServletFileUpload(getFileItemFactory());
            List<FileItem> items = null;
            try {
                parsedReqL = uploadHandler.parseRequest(request);
                items = new ArrayList<FileItem>(parsedReqL);
            } catch (FileUploadException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
                messageUpload.append("Nastala chyba při ukládání. ");
                return "";
            }

            Iterator itr = items.iterator();
            for (Iterator it = items.iterator(); it.hasNext();) {
                FileItem item = (FileItem) it.next();
                if (item.isFormField()) {
                    if (parameter.equals(item.getFieldName())) {
                        return item.getString();
                    }
                }

            }
            messageUpload.append("Chyba při procházení requestu. ");
            return "";
        } else {
            return request.getParameter(parameter);
        }
    }

    private DiskFileItemFactory getFileItemFactory() {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        //Čistič chybuje
        //FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(this.getServletContext());

        fileItemFactory.setSizeThreshold(4 * 1024 * 1024); //do 1 MB se ukládá rovnou
        fileItemFactory.setRepository(tmpDir); // nad 1 MB se ukládá do tempu
        //fileItemFactory.setFileCleaningTracker(fileCleaningTracker);
        return fileItemFactory;
    }

    /**
     * Ukládá multipart data odeslaná z formuláře do db jako entitu Person..
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = null;
        String description = null;
        String municipalty = null;
        String street = null;
        int numOri = 0;
        byte[] image = null;

        try {
            List<FileItem> items = new ArrayList<FileItem>(parsedReqL);
            // Prochazí multipart request
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                //
                if (item.isFormField()) {



                    if ("name".equals(item.getFieldName())) {
                        name = new String(item.get(), "UTF-8");
                        if ("".equals(name)) {
                            messageUpload.append("Vyplňte jméno. ");
                        }


                    } else if ("description".equals(item.getFieldName())) {
                        if ("".equals(item.getString())) {
                            description = "Jsem tajnůstkář";
                        } else {
                            description = new String(item.get(), "UTF-8");
                        }
                    } else if ("municipalty".equals(item.getFieldName())) {
                        municipalty = new String(item.get(), "UTF-8");
                        if ("".equals(municipalty)) {
                            messageUpload.append("Vyplňte město. ");
                        }

                    } else if ("street".equals(item.getFieldName())
                            && !"".equals(item.getString())) {
                        street = new String(item.get(), "UTF-8");
                        if ("".equals(street)) {
                            messageUpload.append("Vyplňte ulici. ");
                        }
                    } else if ("numOri".equals(item.getFieldName())
                            && !"".equals(item.getString())) {
                        try {
                            numOri = Integer.parseInt(item.getString());
                            if ("".equals(item.getString())) {
                                messageUpload.append("Vyplňte číslo popisné. ");
                            }
                        } catch (Exception ex) {
                            messageUpload.append("V čísle popisném není vyplněno číslo. ");
                        }
                    }

                } else {
                    if (item.getSize() == 0) {
                        messageUpload.append("Doplňte obrázek. ");
                    } else {
                        image = item.get();
                    }
                }

            }
        } catch (Exception ex) {
            Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, "Chyba při ukládání souboru", ex);
            messageUpload.append("Chyba při ukládání souboru. ");
            return;
        }


        if (messageUpload.length() == 0) {
            Person person = new Person();
            person.setName(name);
            person.setDescription(description);
            person.setImage(image);
            person.setMunicipalty(municipalty);
            person.setStreet(street);
            person.setNumOri(numOri);
            try {
                person = personWS.getLatAndLon(person);
            } catch (Exception ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, "Osobě nebyly uloženy údaje o souřadnicích.", ex);
                messageUpload.append("Osobě nebyly uloženy údaje o souřadnicích. ");
                return;
            }
            try {
                personDAO.addPerson(person);
            } catch (Exception ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, "Chyba při ukládání v databázi. ");
                messageUpload.append("Chyba při ukládání v databázi. ");
                return;
            }

        }

    }
}
